//
//  AddCircleSecondViewController.m
//  安好
//
//  Created by rlp on 14-11-26.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "AddCircleSecondViewController.h"
#import "PopoverView1.h"
@interface AddCircleSecondViewController ()

@end

@implementation AddCircleSecondViewController

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
    [self hiddenActionView];

    if (self.pop) {
        [self.pop dismiss];
        
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    MyNSLog("self.attentionDict%@",self.attentionDict);

    if (!self.secondCircleArray) {
        self.secondCircleArray = [[NSMutableArray alloc]initWithCapacity:10];

    }
    if (!self.circleModelDatas) {
        self.circleModelDatas = [[NSMutableArray alloc]initWithCapacity:10];

    }
    if (!self.selectDict) {
        self.selectDict = [[NSMutableDictionary alloc]initWithCapacity:10];

    }
    if (!self.attentionArray) {
        self.attentionArray = [[NSMutableArray alloc]initWithCapacity:10];

    }
    if (!self.deleAttentionArray) {
        self.deleAttentionArray = [[NSMutableArray alloc]initWithCapacity:10];
        
    }
    if (!self.attentionDict) {
        self.attentionDict = [[NSMutableDictionary alloc]initWithCapacity:10];
        
    }


    // Do any additional setup after loading the view from its nib.
    [self loadCircleData];
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
    
    
    [self makeNavBarView];

    

    
}
#pragma mark - 设置导航条
-(void)makeNavBarView
{
    
    
    self.centerButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [self.centerButton setTitle:[NSString stringWithFormat:@"%@",self.circleModelData.title] forState:UIControlStateNormal];
    [self.centerButton sizeToFit];
    
    
//    [self.centerButton addTarget:self action:@selector(centerButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.centerButton.frame = CGRectMake(0, 0, self.centerButton.frame.size.width+24, self.centerButton.frame.size.height);

//    UIImageView *titleImage = [[UIImageView alloc]initWithFrame:CGRectMake(self.centerButton.frame.size.width-12, (self.centerButton.frame.size.height-12)/2, 12, 12)];
//    titleImage.image = [UIImage imageNamed:@"添加_下三角"];
//    
//    
//    [self.centerButton addSubview:titleImage];
    
    
 
    
    
    
    
    self.navigationItem.titleView = self.centerButton;
    
    
//    self.navigationItem.title = [NSString stringWithFormat:@"%@",self.circleModelData.title];
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    
    
    
    self.rightButton = [[UIButton alloc]initWithFrame:CGRectZero];
    
    
    [self.rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:BUTTON_TEXTLABEL_FOUNT_SIZE];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];

    
    NSInteger isAll=0;//是否未全关注状态
    for (int i=0; i<self.selectDict.count; i++) {
        if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%d",i]] isEqualToString:@"1"]) {
            isAll++;
            
        }
    }
    if ((self.selectDict.count-1) == isAll) {//按钮显示取消关注
        [self.rightButton setTitle:@"取消全部" forState:UIControlStateNormal];
    }else{
        [self.rightButton setTitle:@"关注全部" forState:UIControlStateNormal];

    }
    [self.rightButton sizeToFit];

    self.navigationItem.rightBarButtonItem = rightBarButtonItem;

    
}
#pragma mark -
#pragma mark -- click
-(void)leftButtonClicked:(UIButton *)sender
{
    
    if (self.attentionArray.count!=0) {
        [self.attentionArray removeAllObjects];
    }
    if (self.deleAttentionArray.count!=0) {
        [self.deleAttentionArray removeAllObjects];
    }
    
    
    if (self.attentionArray.count==0) {
        for (int i = 0; i<self.selectDict.count; i++) {
            if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%d",i]] isEqualToString:@"1"]) {
               [self.attentionArray addObject: [self.secondCircleArray objectAtIndex:i]];
            }else{
                [self.deleAttentionArray addObject: [self.secondCircleArray objectAtIndex:i]];

            }
        }
    }
//    [self.delegate selectedWithAttentions:self.attentionArray];
    [self.delegate selectedWithAttentions:self.attentionArray delAttentions:self.deleAttentionArray];

    [self.navigationController popViewControllerAnimated:YES];

    
}
-(IBAction)centerButtonClicked:(UIButton *)sender{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    
    NSMutableDictionary *titAndPid = [[NSMutableDictionary alloc]initWithCapacity:10];
    for (int i=0; i<self.circleModelDatas.count; i++) {
        [titAndPid setObject:[(CircleModelData *)[self.circleModelDatas objectAtIndex:i] gid] forKey:[(CircleModelData *)[self.circleModelDatas objectAtIndex:i] title]];
    }
    
    
    
    NSArray *titles = [titAndPid allKeys];
    self.pop = [[PopoverView alloc] initWithPoint:point titles:titles images:nil];
    __block AddCircleSecondViewController *mySelf = self;
    self.pop.selectRowAtIndex = ^(NSInteger index){
        MyNSLog("select index:%d", index);
                [mySelf.centerButton setTitle:[titles objectAtIndex:index] forState:UIControlStateNormal];

                mySelf.circleModelData =[mySelf.circleModelDatas objectAtIndex:index];
                [mySelf loadCircleData];
                
    };
    [self.pop show];
}
-(IBAction)selectButtonClick:(id)sender{
    UIButton *button =(UIButton*)sender;
    NSInteger tags = button.tag;
    if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%d",tags]] isEqualToString:@"1"]) {
        [button setImage:[UIImage imageNamed:@"添加_未添加"] forState:UIControlStateNormal];
        [self.selectDict setObject:[NSString stringWithFormat:@"%d",0] forKey:[NSString stringWithFormat:@"%d",tags]];
    }else if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%d",tags]] isEqualToString:@"0"]){
        [button setImage:[UIImage imageNamed:@"添加_添加"] forState:UIControlStateNormal];
        [self.selectDict setObject:[NSString stringWithFormat:@"%d",1] forKey:[NSString stringWithFormat:@"%d",tags]];

    }
    
    [self attentionButtonShowTitle];
}
/**
 *  右上角button的显示
 */
-(void)attentionButtonShowTitle{
    NSInteger isAll=0;//是否未全关注状态
    for (int i=0; i<self.selectDict.count; i++) {
        if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%d",i]] isEqualToString:@"1"]) {
            isAll++;
            
        }
    }
    if (self.selectDict.count == isAll) {//按钮显示取消关注
        [self.rightButton setTitle:@"取消全部" forState:UIControlStateNormal];
    }else{
        [self.rightButton setTitle:@"关注全部" forState:UIControlStateNormal];
        
    }
}

-(IBAction)rightButtonClicked:(id)sender{
    UIButton *button = (UIButton *)sender;
    if ([button.titleLabel.text isEqualToString:@"关注全部"]) {
        
        for (int i=0; i<self.selectDict.count; i++) {
            [self.selectDict setObject:[NSString stringWithFormat:@"%d",1] forKey:[NSString stringWithFormat:@"%d",i]];
        }
        [self.rightButton setTitle:@"取消全部" forState:UIControlStateNormal];
        
    }else if ([button.titleLabel.text isEqualToString:@"取消全部"]) {
        for (int i=0; i<self.selectDict.count; i++) {
            [self.selectDict setObject:[NSString stringWithFormat:@"%d",0] forKey:[NSString stringWithFormat:@"%d",i]];
        }
        [self.rightButton setTitle:@"关注全部" forState:UIControlStateNormal];

    }
    
    
    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark -- 数据加载
-(void)loadCircleData{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:[NSString stringWithFormat:@"%@",self.circleModelData.gid] forKey:@"pid"];
    [dict setObject:@"20" forKey:@"pagesize"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_LIST] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            [self.secondCircleArray removeAllObjects];
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                CircleModelData *circlemodelData = [CircleModelData modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                [self.secondCircleArray addObject:circlemodelData];
                
                MyNSLog("circlemodelData.title%@,%@,%@",circlemodelData.title,circlemodelData.gid,[self.attentionDict allKeysForObject:circlemodelData.gid]);
                /**
                 *  标记选中
                 */
                if ([self.attentionDict allKeysForObject:circlemodelData.gid].count>0) {
                    [self.selectDict setObject:[NSString stringWithFormat:@"%d",1] forKey:[NSString stringWithFormat:@"%d",i]];

                }else{
                    [self.selectDict setObject:[NSString stringWithFormat:@"%d",0] forKey:[NSString stringWithFormat:@"%d",i]];

                }
                
                
                
            }
            
//            [self loadbuttonimageTag];
            [self attentionButtonShowTitle];
            [self.tableView reloadData];
            
        }
        
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger number=0;
    
    number = 1;
    return number;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger number=0;
    
    number = self.secondCircleArray.count;
    return number;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger hight=ADD_CIRCLE_SECOND_LEVEL_TABLEVIEWCELL_HIGHT;
    return hight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    

    static NSString *ID=nil;
    AddCircleSecondLevelTableViewCell *cell = nil;
    if (kScreenWidth == 414) {
        ID=@"tableViewCell414";
    }else{
        ID=@"tableViewCell";
    }
    cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddCircleSecondLevelTableViewCell" owner:self options:nil] lastObject];

        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddCircleSecondLevelTableViewCell" owner:self options:nil] firstObject];

        }
        /**
         *  线条的处理
         */
        
        UIView *bottomLineView = [[UIView alloc]init];
        
//        if (indexPath.row != self.secondCircleArray.count - 1)
//        {
//            bottomLineView.frame = CGRectMake(90, cell.contentView.height-0.5,kScreenWidth-90 - 5, 0.5);
//        }
//        else
//        {
            bottomLineView.frame = CGRectMake(0, cell.contentView.height-0.5, kScreenWidth, 0.5);
//        }
        
        bottomLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
        [cell.contentView addSubview:bottomLineView];
    }
    
    
    CircleModelData *circleMdata =[self.secondCircleArray objectAtIndex:indexPath.row];
    // Configure the cell...
    [cell.icon setImageURLStr:circleMdata.icon placeholder:nil];
    
    [(AddCircleSecondLevelTableViewCell *)cell title].text = [[self.secondCircleArray objectAtIndex:indexPath.row] title];
    [(AddCircleSecondLevelTableViewCell *)cell subtitle].text =[[self.secondCircleArray objectAtIndex:indexPath.row] lastposttitle];
    
    [[(AddCircleSecondLevelTableViewCell *)cell thread] setTitle:[NSString stringWithFormat:@" %@",[[self.secondCircleArray objectAtIndex:indexPath.row] threads]] forState:UIControlStateNormal];
    [[(AddCircleSecondLevelTableViewCell *)cell post] setTitle:[NSString stringWithFormat:@" %@",[[self.secondCircleArray objectAtIndex:indexPath.row] posts]] forState:UIControlStateNormal];
    
    
    if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]] isEqualToString:@"0"]) {
        [[(AddCircleSecondLevelTableViewCell *)cell selectButton] setImage:[UIImage imageNamed:@"添加_未添加"] forState:UIControlStateNormal];
    }else if ([[self.selectDict objectForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]] isEqualToString:@"1"]){
        [[(AddCircleSecondLevelTableViewCell *)cell selectButton] setImage:[UIImage imageNamed:@"添加_添加"] forState:UIControlStateNormal];

    }
    
    [[(AddCircleSecondLevelTableViewCell *)cell selectButton] addTarget:self action:@selector(selectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [(AddCircleSecondLevelTableViewCell *)cell selectButton].tag = indexPath.row;
    

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    
}

@end
